package com.traffic.between.service;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.Base64;
import com.traffic.between.util.SecurityUtil;
import com.traffic.between.util.Xml2JsonUtil;

import net.sf.json.JSONObject;

public class JuHeServiceImpl {
	private static Logger logger = Logger.getLogger(JuHeServiceImpl.class);
	public static JuHeServiceImpl service = new JuHeServiceImpl();

	private static String HOST_ORDER_PATH = BetweenProperties.JUHE_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.JUHE_ORDERSTATUS_URL;
	private static String JUHE_APPKEY = BetweenProperties.JUHE_APPKEY;
	private static String JUHE_SECURITYKEY = BetweenProperties.JUHE_SECURITYKEY;

	
	public String order(String productId, String phoneNo, String cstmOrderNo) {
	
		String resp = "";
		StringBuilder sb = null;
        try {
        	String dateformat = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    		String signStr = (new StringBuilder(String.valueOf(JUHE_APPKEY))).append(cstmOrderNo)
    				.append(JUHE_SECURITYKEY).append(JUHE_APPKEY).append(dateformat).toString();
    		signStr = Base64.encode(SecurityUtil.getDigestMD5(signStr));
    		sb = new StringBuilder();
			sb.append("<request>");
			sb.append("<head>");
			sb.append("<custInteId>" + JUHE_APPKEY + "</custInteId>");
			sb.append("<echo>" + JUHE_APPKEY + "</echo>");
			sb.append("<orderId>" + cstmOrderNo + "</orderId>");
			sb.append("<timestamp>" + dateformat + "</timestamp>");
			sb.append("<orderType>1</orderType>");
			sb.append("<version>1.0</version>");
			sb.append("<chargeSign>" + signStr + "</chargeSign>");
			sb.append("</head>");
			sb.append("<body>");
			sb.append("<item>");
			sb.append("<packCode>" + productId + "</packCode>");
			sb.append("<mobile>" + phoneNo + "</mobile>");
			sb.append("<effectType>1</effectType>");
			sb.append("</item>");
			sb.append("</body>");
			sb.append("</request>");
			
			logger.info("bsm-聚合订购请求的参数:"+sb.toString());
			CloseableHttpClient client = HttpClients.createDefault();
			  
			HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
	        
			StringEntity entity = new StringEntity(sb.toString(),"utf-8");//解决中文乱码问题    
			entity.setContentEncoding("utf-8");    
            entity.setContentType("text/xml");  
            httpPost.setEntity(entity);
            
            HttpResponse response = client.execute(httpPost);
        	int statusCode = response.getStatusLine().getStatusCode();
        	if (200==statusCode) {
				resp = EntityUtils.toString(response.getEntity());
				logger.info("bsm-聚合订购响应的参数:"+resp);
				String body = Xml2JsonUtil.xml2JSON(resp);
				JSONObject resultJson = JSONObject.fromObject(body);
				JSONObject json = (JSONObject) resultJson.get("response");
				String result = json.getString("result");
				if ("0000".equals(result)) {
				
					resp = "{\"resultCode\": \"00\",\"resultMsg\":\"订单成功\"}";
				} else {
					resp = "{\"resultCode\": \"01\",\"resultMsg\":\"订单失败\"}";
	
				}
			}

		} catch (Exception e) {
			logger.info("bsm- 聚合订购请求响应的异常信息:"+e);
		}
        
        return resp;
		
	}
	
	
	
	public String orderStatus(String cstmOrderNo) {
		logger.info("bsm- 聚合状态JuHeServiceImpl.orderStatus() 查询请求cstmOrderNo = " + cstmOrderNo);
		String resp = "";		
		try {
			String dateformat = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String signStr = (new StringBuilder(String.valueOf(JUHE_APPKEY))).append(JUHE_SECURITYKEY)
					.append(JUHE_APPKEY).append(dateformat).toString();
			signStr = Base64.encode(SecurityUtil.getDigestMD5(signStr));
			StringBuilder sb = new StringBuilder();
			sb.append("<request>");
			sb.append("<head>");
			sb.append("<custInteId>" + JUHE_APPKEY + "</custInteId>");
			sb.append("<echo>" + JUHE_APPKEY + "</echo>");
			sb.append("<timestamp>" + dateformat + "</timestamp>");
			sb.append("<version>1.0</version>");
			sb.append("<chargeSign>" + signStr + "</chargeSign>");
			sb.append("</head>");
			sb.append("<body>");
			sb.append("<item>");
			sb.append("<orderIds>" + cstmOrderNo + "</orderIds>");
			sb.append("</item>");
			sb.append("</body>");
			sb.append("</request>");
			
			logger.info("bsm-聚合查询状态请求的参数:"+sb.toString());
			
			CloseableHttpClient client = HttpClients.createDefault();
			  
			HttpPost httpPost = new HttpPost(HOST_ORDERSTATUS_PATH);
	        
			StringEntity entity = new StringEntity(sb.toString(),"utf-8");//解决中文乱码问题    
			entity.setContentEncoding("utf-8");    
            entity.setContentType("text/xml");  
            httpPost.setEntity(entity);
            
            HttpResponse response = client.execute(httpPost);
        	int statusCode = response.getStatusLine().getStatusCode();
        	logger.info("聚合响应response " + response.getEntity());
        	if (200==statusCode) {
				resp = EntityUtils.toString(response.getEntity());
				
				logger.info("bsm-聚合查询订单状态响应的参数:"+resp);
				String head = Xml2JsonUtil.requestHeadXmlToJson(resp);
				JSONObject headJson = JSONObject.fromObject(head);
				String result = headJson.getString("result");
				String body = Xml2JsonUtil.requestBodyXmlToJson(resp);
				
				// 返回0000为充值请求提交成功，其他错误码为失败
				JSONObject bodyJson = JSONObject.fromObject(body);
				String state = bodyJson.getString("state");
				if ("0000".equals(result)) {
					// -1 无此订单号 0 充值中 1 成功 2 失败
					if ("0".equals(state)) {
						resp = "{\"resultCode\": \"00\",\"resultMsg\":\"订购中\"}";
					} else if ("1".equals(state)) {
						resp = "{\"resultCode\": \"02\",\"resultMsg\":\"订单成功\"}";
					} else {
						resp = "{\"resultCode\": \"01\",\"resultMsg\":\"订购失败\"}";
					}
				} else {
					logger.info("聚合查询状result"+result);
					resp = "{\"resultCode\": \"01\",\"resultMsg\":\"订购失败\"}";
				}
				
			}
        
		} catch (Exception e) {
			logger.info("bsm- 聚合订购请求响应的异常信息:"+e);
			resp = "{\"resultCode\": \"00\",\"resultMsg\":\"订购中\"}";
		}
		return resp;
	}
	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5 " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}
}
